package com.example.xiaoxueqixiangmu.jiemian;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xiaoxueqixiangmu.R;
import com.example.xiaoxueqixiangmu.bean.Seat;
import com.example.xiaoxueqixiangmu.bean.Train;
import com.example.xiaoxueqixiangmu.utils.Constant;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class chepiaoyudingActivity extends AppCompatActivity {
    private List<HashMap<String,Object>> dataList;
    private ListView lv;
    private TextView TV8,txtT1;
    private Button BT1,BT2;
    private static final String TAG = "chepiaoyudingActivity";
    private List<Train> listTrain;
    private MyListViewAdapter myListViewAdapter ;
    private ArrayList<HashMap<String,String>> dataArray;


    private String fromStationName , toStationName, startTrainDate;
    int myear;
    int mmonth;
    int mday;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chepiaoyuding);
        TV8=findViewById(R.id.TV8);
        BT2=findViewById(R.id.BT2);
        BT1=findViewById(R.id.Bt1);
        txtT1 = findViewById(R.id.txtT1);


        // -- 获取参数-- 出发车站 ， 到达车站，出发时间（年，月，日）
        startTrainDate = getIntent().getStringExtra("startTrainDate");
        TV8.setText(startTrainDate);
        fromStationName = getIntent().getStringExtra("fromStationName");
        toStationName = getIntent().getStringExtra("toStationName");
        myear = getIntent().getIntExtra("myear",0);
        mmonth = getIntent().getIntExtra("mmonth",0);
        mday = getIntent().getIntExtra("mday",0);
        final String goCity = getIntent().getStringExtra("goCity");
        final String backCity = getIntent().getStringExtra("backCity");
        startTrainDate = myear+"-"+mmonth+"-"+mday;
        lv=findViewById(R.id.lv);
        dataArray = new ArrayList<>();
        myListViewAdapter = new MyListViewAdapter(this,dataArray);

        // listview 设置子项点击事件，如果子项被点击 在Intent中收集信息再页面跳转
        lv.setAdapter(myListViewAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Train train = listTrain.get(position);
                Map<String, Seat> seats = train.getSeats();
                Intent intent = new Intent(chepiaoyudingActivity.this,chepiaoyuding2Activity.class);
                intent.putExtra("seats", (Serializable) seats);
                intent.putExtra("transNo",train.getTrainNo());
                String str = train.getStartTime()+"-"+train.getArriveTime()+",历时"+train.getDurationTime();
                intent.putExtra("content",str);
                intent.putExtra("fromStationName",fromStationName);
                intent.putExtra("toStationName",toStationName);
                intent.putExtra("startTrainDate",startTrainDate);
                intent.putExtra("myear",myear);
                intent.putExtra("mmonth",mmonth);
                intent.putExtra("mday",mday);
                intent.putExtra("listTrain", (Serializable) listTrain);
                intent.putExtra("goCity",goCity);
                intent.putExtra("backCity",backCity);
                HashMap<String, String> hashMap = dataArray.get(position);
                intent.putExtra("trainNo",train.getTrainNo());
                Log.i(TAG, "onItemClick: sss"+train.getTrainNo());
                startActivity(intent);
            }
        });


        // 导航栏，生成向左的箭头
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);

        txtT1.setText(goCity+"->"+backCity);

        //日期的选择
        //BT1查询前一天的车票信息
        BT1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mday -= 1;
                if( mday <= 0 ){
                    mmonth -= 1;
                    mday = 31;
                }
                startTrainDate = myear+"-"+mmonth+"-"+mday;
                TV8.setText(startTrainDate);
                queryFromServerWithDate(startTrainDate);
                confData();
            }
        });

        //  BT2查询后一天的车票信息
        BT2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mday += 1;
                if( mday >= 31 ){
                    mmonth += 1;
                    mday = 1;
                }
                startTrainDate = myear+"-"+mmonth +"-"+mday;
                TV8.setText(startTrainDate);
                queryFromServerWithDate(startTrainDate);

            }
        });

    }

    // 向服务器发送 出发车站 ， 目的车站 ， 出发时间等数据 。 准备出发
    public void queryFromServerWithDate(final String date){
        final ProgressDialog progressDialog = new ProgressDialog(chepiaoyudingActivity.this);
        progressDialog.setTitle("加载数据中...");
        progressDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 从 SharePerference 中获取Cookie对应的JSESSIONID
                SharedPreferences sharedPreferences = getSharedPreferences("userinfo",MODE_PRIVATE);
                String JSESSIONID = sharedPreferences.getString("cookie", "");
                Log.i(TAG, "run: "+JSESSIONID);

                // 发送Http请求到服务器，请求该出发车站到到达车站的火车列表
                OkHttpClient okHttpClient = new OkHttpClient();
                FormBody formBody = new FormBody.Builder().add("fromStationName",fromStationName)
                        .add("toStationName",toStationName)
                        .add("startTrainDate",date)
                        .build();
                Request request = new Request.Builder().url(Constant.Host+"/otn/TrainList").post(formBody).addHeader("cookie",JSESSIONID).build();
                Call call = okHttpClient.newCall(request);
                try {
                    final String string = call.execute().body().string();
                    Log.i(TAG, "run: "+string);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.dismiss();

                            // 将获取到的数据进行解析为 List, 再将数据放入数据源让适配器重新适配
                            if(!string.equals("[]")) {
                                listTrain = new Gson().fromJson(string,new TypeToken<List<Train>>() {}.getType());
                                confData();
                            }else {
                                if(listTrain != null){
                                    dataArray.clear();
                                    myListViewAdapter.notifyDataSetChanged();
                                }
                            }

                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    // 将从服务器获取到的数据加载到本地中
    public void confData(){
        dataArray.clear();
        for (int i = 0; i < listTrain.size(); i++) {
            Train train = listTrain.get(i);
            Map<String, Seat> seats = train.getSeats();
            HashMap<String,String> hashMap = new HashMap<>();
            hashMap.put("trainsNo",train.getTrainNo());
            hashMap.put("txtStartTime",train.getStartTime());
            hashMap.put("txtArriveTime",train.getArriveTime()+"("+train.getDayDifference()+"日)");
            String info = "";
            Set<String> keySet = seats.keySet();
            Iterator<String> iterator = keySet.iterator();
            while ( iterator.hasNext() ){
                Seat seat = seats.get(iterator.next());
                info += seat.getSeatName()+":"+seat.getSeatNum()+" ";
            }

            hashMap.put("txtSeats",info);
            dataArray.add(hashMap);
        }


        myListViewAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch ( item.getItemId() ){
            case android.R.id.home:
                chepiaoyudingActivity.this.finish();
                break;
        }
        return true;
    }
}